<!-- 退货产品 - 表单编辑页面 -->
<template>
	<div class="page_rela_container">
		<div class="scroll_auto flex_cell">

    <!-- title -->
    <div class="page-content-title">
      <!-- 当前位置：新增仓储产品-->
      {{ $t('label_current_position') }}：{{ $t('label_create_return_goods_product') }}
    </div>
    <el-form ref="formEl" :model="formValue" :rules="rules" label-width="130px">

      <ex_header_spiler :title="$t('label_pms_product_base_info')"></ex_header_spiler>
      <el-row style="margin-top: 20px;">
        <el-col>
          <!-- 产品名称 -->
          <el-form-item :label="$t('label_pms_product_name')" prop="productName">
            <el-input style="width: 270px;" v-model="formValue.productName"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col>
          <!-- 产品编码 -->
          <el-form-item :label="$t('label_pms_product_code')" prop="productCode">
            <el-input style="width: 270px;" v-model="formValue.productCode"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="2">
          <!-- 产品描述 -->
          <el-form-item :label="$t('label_pms_description')">
            <el-input style="width: 270px;" type="textarea" v-model="formValue.remark"></el-input>
          </el-form-item>
        </el-col>
      </el-row>


      <!-- 产品报价信息 -->
      <ex_header_spiler title="标准价卡"></ex_header_spiler>
      <div style="position: relative;">

        <!-- 添加价卡版本 -->
        <el-button @click="adTabConfig" style="position: absolute;  top: -32px; right: 20px; z-index: 999; "
          icon="el-icon-plus">添加价卡版本</el-button>

        <ex-button-delete style="position: absolute;  top: 60px; right: 0; z-index: 999; "
          v-if="formValue.standardPriceVersions && formValue.standardPriceVersions.length > 0 && activeName != getTabId(formValue.standardPriceVersions[0])"
          message="确定删除当前产品价卡配置？" label="删除当前配置" byAction :delAction="() => {
        formValue.standardPriceVersions = formValue.standardPriceVersions.filter(tab => getTabId(tab) != activeName);
        activeName = getTabId(formValue.standardPriceVersions[0]);
      }"></ex-button-delete>

        <el-tabs v-if="formValue.standardPriceVersions && formValue.standardPriceVersions.length > 0"
          v-model="activeName" type="card">
          <el-tab-pane v-for="(item, index) in formValue.standardPriceVersions" :label="getTabTitle(item)"
            :name="getTabId(item)" :key="item.tabId">
            <returnGoodsProductPriceCfg ref="returnGoodsProductPriceCfgRef" :versionStartTimeDisabled="index === 0"
              :priceVersionId="item.id" :standardServices="standardServices" :priceUnitMap="priceUnitMap"
              v-model="formValue.standardPriceVersions[index]">
            </returnGoodsProductPriceCfg>
          </el-tab-pane>
        </el-tabs>

        <div v-else style="padding-left: 100px; display: flex; align-items: center;  color: #d41515; ">
          <i class="el-icon-warning" style="margin-right: 8px;"></i>
          还没添加价卡版本
        </div>

      </div>

    </el-form>

  </div>
  	<div class="page_rela_bottom_area">
      <!-- 保存 -->
      <el-button type="primary" @click="submitForm">{{ $t('label_save') }}</el-button>
      <!-- 取消 -->
      <el-button @click="return_page_back()">{{ $t('label_cancel') }}</el-button>
    </div>

  </div>
</template>
<script>
import router_params from '@/mixin/router_params';

import returnGoodsProductPriceCfg from '@/component/pms/return_goods_product_price_cfg.vue'


export default {
  // title: "新增" + moduleName,
  components: { returnGoodsProductPriceCfg },
  mixins: [router_params],
  data() {

    return {
      edit: false,
      "operateType": "",
      "formValue": {
        productName: '',
        productCode: '',
        remark: '',
        "standardPriceVersions": [],
      },
      "activeName": "",
      // 服务项
      "standardServices": [],
      "priceUnitMap": {},

      "editFormData": {},
      rules: {
        productName: [{ required: true, message: this.$t('tip_can_no_empty'), trigger: 'blur' }],
        productCode: [{ required: true, message: this.$t('tip_can_no_empty'), trigger: 'blur' }]
      }

    };
  },

  created() {
    this.iniDefaultConfigs()

    if (this.formValue.standardPriceVersions && this.formValue.standardPriceVersions.length > 0) {
      this.activeName = this.getTabId(this.formValueCache.standardPriceVersions[0])
    }

  },

  mounted() {
  },

  methods: {
    adTabConfig() {
      let sample = {
        id: '',
        versionId: '-1',
        versionName: '',
        versionType: '',
        status: 'ENABLE',
        versionTag: '',
        productId: '',
        returnMainPrice: {
          currencyType: "CNY",
          standardPrices: [],
          addtionalPrices: []
        },
      }

      if (this.formValue.standardPriceVersions && this.formValue.standardPriceVersions.length > 0) {
        Object.assign(sample, JSON.parse(JSON.stringify(this.formValue.standardPriceVersions[this.formValue.standardPriceVersions.length - 1])))
        let lastTime = sample.versionEndTime
        sample.versionStartTime = parseInt(lastTime) + 86400000
        sample.versionEndTime = parseInt(lastTime) + 31536000000
        sample.id=''
      } else {
        let lastTime = new Date().getTime()
        // sample.daterange = [lastTime, parseInt(lastTime) + 31536000000]
        sample.versionStartTime = lastTime
        sample.versionEndTime = parseInt(lastTime) + 31536000000
      }

      sample.tabId = 'id_' + (Math.random() + '').replace('.', '')

      this.formValue.standardPriceVersions.push(sample)

      this.activeName = this.getTabId(sample)
    },

    getTabTitle(item) {
      return this.$dateFormatDate(item.versionStartTime) + ' 至 ' + this.$dateFormatDate(item.versionEndTime)
    },

    getTabId(item) {
      return 'tab_' + item.tabId
    },

    init_data_default(into_params) {
      if (into_params.id) {
        this.loading = true
        this.$ajax({
          url: "/fms-api/product/PmsReturnProductRpc/detail.json",
          method: 'post',
          data: { id: into_params.id },
          success: (res) => {
            if (res && res.data) {
              Object.assign(this.formValue,res.data)
            }

            this.loadEditFormDataByParams()
            this.$emit("tagModifyLabel", { _key: 'label_name_code', name: this.$t('label_edit_return_goods_product'), code: res.data.productName })

          }
        })
      } else {
        this.adTabConfig()
        this.$emit("tagModifyLabel", "label_create_return_goods_product")
      }

    },
    // 初始化编辑表单
    loadEditFormDataByParams() {
      // 对数组内复制的对象进行处理，赋值 tabId
      if (this.formValue.standardPriceVersions && this.formValue.standardPriceVersions.length > 0) {

        this.formValue.standardPriceVersions.forEach(e => {
          e.tabId = 'id_' + (Math.random() + '').replace('.', '')
        })
        this.activeName = this.getTabId(this.formValue.standardPriceVersions[0])

      }
    },


    // 加载默认常量信息
    iniDefaultConfigs() {
      this.$ajax({
        url: '/fms-api/product/PmsReturnProductRpc/getDefaultServiceForms.json',
        success: (res) => {
          this.standardServices = res.data.rows
          this.loadEditFormDataByParams()
        }
      });

      this.$ajax({
        url: '/fms-api/product/PriceUnitRpc/getPriceUnitMap.json',
        success: (res) => {
          if (res && res.data) {
            this.priceUnitMap = res.data
          }
        }
      });
    },


    // 提交表单
    submitForm() {
      this['$refs']['formEl'].validate((valid,obj) => {

        if (_.isEmpty(this.formValue.standardPriceVersions)) {
          this.$message({
            showClose: true,
            message: '请添加价卡版本',
            type: 'warning'
          })
          return
        }

        let validBle = true
        this.$refs['returnGoodsProductPriceCfgRef'].forEach(item => {
          item['$refs']['formRef'].validate((valid,obj) => {
            if(!valid){
              validBle = valid
            }
          })
        })

        if (valid&&validBle) {
          this.$ajax({
            url: '/fms-api/product/PmsReturnProductRpc/saveUpdate.json',
            type: 'json',
            data: this.formValue,
            success: () => {
              this.$message.success(this.$t('tip_submit_success'))
              this.return_emit(null, "reload")
              this.return_page_back()
            }
          });

        } else {
          return false
        }
      });
    }
  }
};

</script>
<style>
.product-line-limit-div,
.product-line-limit-div-2 {
  display: flex;
}


.product-line-limit-div .product-line-limit-col {
  width: 220px;
  text-align: center;
  margin-right: 10px;
}

.product-line-limit-div-2 div {
  width: 300px;
  /*text-align: center;*/
  margin-right: 10px;
}

.price-cal-div-row {
  display: flex;
}

.price-cal-div-row .price-cal-col {
  width: 120px;
  text-align: center;
}

.price-cal-div-row div {
  margin-right: 8px;
  text-align: center;
}
</style>
